package sqlplus;

import java.sql.*;
import java.io.*;
public class Upfile {
	public static void main(String args[]) {
		Connection con = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		Blob blob = null;
		int id = 4;
		String flieName = ("001.jpg");
		try {
			con = JdbcUtil.getConn();
			con.setAutoCommit(false);
			//委托oracle给我们
			String sql="insert into lotus values(?,?,empty_blob())";
			ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ps.setString(2,flieName);
			ps.executeUpdate();
			//******************//
			sql="select filecontent from lotus where id=? for update";
			JdbcUtil.close(null, ps, null);
			
			ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if(rs.next()){
				blob = rs.getBlob(1);
			}
			
			InputStream in = 
				new FileInputStream(flieName);
			OutputStream out = 
				blob.setBinaryStream(0);
			byte[] content = new byte[in.available()];
			in.read(content);
			out.write(content);
			in.close();out.close();
			sql="update lotus set filecontent=? where id=?";
			JdbcUtil.close(rs, ps, null);
			ps = con.prepareStatement(sql);
			ps.setBlob(1,blob);
			ps.setInt(2, id);
			ps.executeUpdate();
			con.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (Exception ee) {
				ee.printStackTrace();
			}
		} finally {
			JdbcUtil.close(null,ps,con);
		}

	}

}
